<template>
  <el-form ref="userRef" :model="form" :rules="rules" label-width="auto">
    <el-form-item label="姓名:" prop="nickname">
      <el-input v-model="form.nickname" maxlength="30" />
    </el-form-item>
    <el-form-item label="手机号码:" prop="phone">
      <el-input v-model="form.phone" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱:" prop="email">
      <el-input v-model="form.email" maxlength="50" />
    </el-form-item>
    <el-form-item label="性别:">
      <el-radio-group v-model="form.gender">
        <el-radio v-for="dict in sys_user_sex" :key="dict.value" :value="JSON.parse(dict.value)">{{ dict.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="个人简介:">
      <el-input v-model="form.remark" type="textarea" placeholder="请输入个人简介" :rows="3" maxlength="300" show-word-limit></el-input>
    </el-form-item>
    <el-form-item label=" ">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { updateUser } from "@/api/system/user"
import useUserStore from "@/store/modules/user"

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const { sys_user_sex } = proxy.useDict("sys_user_sex")

const props = defineProps({
  user: {
    type: Object
  }
})

const form = ref({})
const rules = ref({
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  phone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }]
})

/** 提交按钮 */
function submit() {
  proxy.$refs.userRef.validate(valid => {
    if (valid) {
      updateUser(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        userStore.nickname = form.value.nickname
        userStore.phone = form.value.phone
        userStore.email = form.value.email
        userStore.remark = form.value.remark
      })
    }
  })
}

/** 关闭按钮 */
function close() {
  proxy.$tab.closePage()
}

// 回显当前登录用户信息
watch(() => props.user, user => {
  if (user) {
    form.value = { userId: user.userId, nickname: user.nickname, phone: user.phone, email: user.email, gender: user.gender, remark: user.remark }
  }
},{ immediate: true })
</script>
